package com.example.news;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.news.dao.LoginDao;

public class MainActivity extends AppCompatActivity {
    Button btnlogin=null;
    EditText etusername=null;
    EditText etpassword=null;
    private LoginDao dao;
    private Button btnregister=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //将控件变量与控件绑定
        btnlogin=(Button)findViewById(R.id.btnlogin);
        etusername=(EditText)findViewById(R.id.etusername);
        etpassword=(EditText)findViewById(R.id.etpassword);
        btnregister=(Button)findViewById(R.id.btnregister);
        //读取数据
        dao=new LoginDao(this);
        //登录按钮功能实现
        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (dao.login(etusername.getText().toString(), etpassword.getText().toString())) {
                        Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_SHORT).show();
                        String txtusername = etusername.getText().toString().trim();
                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                        etusername.setText("");
                        etpassword.setText("");
                    } else {
                        Toast.makeText(getApplicationContext(), "登录失败！", Toast.LENGTH_SHORT).show();
                        etusername.setText("");
                        etpassword.setText("");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                    etusername.setText("");
                    etpassword.setText("");
                }
            }
        });
        //注册按钮功能实现
        btnregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
                MainActivity.this.finish();
            }
        });
    }
}
